package main

import (
	"fmt"
	"net/http"

	"github.com/spf13/cobra"
)

func addControlCommands() {
	controlCmd := &cobra.Command{
		Use:   "control",
		Short: "设备控制操作",
	}

	// 新增：设备启动命令
	startCmd := &cobra.Command{
		Use:     "start <通讯映射名>",
		Short:   "启动设备采集程序",
		Example: `  iotadmin control start serial-mapping-1`,
		Args:    cobra.ExactArgs(1), // 确保接收两个参数
		Run: func(cmd *cobra.Command, args []string) {
			ctx := getContext(cmd)
			mappingName := args[0]

			if ctx.Verbose {
				fmt.Printf("正在启动设备采集 %s \n", mappingName)
			}

			if err := startDevice(mappingName); err != nil {
				fmt.Printf("❌ 设备启动失败: %v\n", err)
				return
			}

			fmt.Printf("✅ 设备 %s 采集程序已成功启动\n", mappingName)
		},
	}

	// 添加命令到命令组
	controlCmd.AddCommand(startCmd)
	RootCmd.AddCommand(controlCmd)
}

func startDevice(mappingName string) error {
	url := fmt.Sprintf("http://%s/device/start/%s", ConsoleAddr(), mappingName)

	req, err := http.NewRequest("POST", url, http.NoBody)
	if err != nil {
		return fmt.Errorf("创建请求失败: %w", err)
	}

	// 设置必要的请求头
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("请求发送失败: %w", err)
	}
	defer resp.Body.Close()

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("服务器返回错误状态码: %d", resp.StatusCode)
	}
	return nil
}

// 模拟实现 - 实际应用中替换为具体逻辑
func sendDeviceCommand(deviceID, command string, params map[string]string) error {
	fmt.Printf("发送命令到设备 %s: %s\n", deviceID, command)
	if len(params) > 0 {
		fmt.Println("命令参数:")
		for k, v := range params {
			fmt.Printf("  %s = %s\n", k, v)
		}
	}
	return nil
}

func writeDeviceParam(argIdx, value string) error {
	return nil
}
